<template>
  <!-- 搜索区域：包含发货单搜索表单 -->
  <div class="search-container">
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form" label-width="80px">
        <!-- 发货单编号搜索项 -->
        <el-form-item label="发货单编号">
          <el-input v-model="searchForm.deliveryNumber" placeholder="请输入发货单编号" clearable @keyup.enter="handleSearch"
            class="search-input" />
        </el-form-item>

        <!-- 快递公司搜索项 -->
        <el-form-item label="快递公司">
          <el-input v-model="searchForm.courierName" placeholder="请输入快递公司名称" clearable @keyup.enter="handleSearch"
            class="search-input" />
        </el-form-item>

        <!-- 发货单状态搜索项 -->
        <el-form-item label="发货单状态">
          <el-select v-model="searchForm.status" placeholder="请选择发货单状态" clearable @change="handleSearch"
            class="search-select">
            <el-option v-for="status in deliveryStatusOptions" :key="status.value" :label="status.label"
              :value="status.value" />
          </el-select>
        </el-form-item>

        <!-- 操作按钮组 -->
        <el-form-item class="button-group">
          <el-button type="primary" @click="handleSearch" class="search-button">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset" class="reset-button">
            <el-icon>
              <Refresh />
            </el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <!-- 表格区域：展示发货单列表数据 -->
  <el-card class="table-card">
    <!-- 表格头部：包含标题和操作按钮 -->
    <template #header>
      <div class="table-header">
        <span>发货单列表</span>
        <div>
          <!-- 新增发货单按钮 -->
          <el-button type="primary" @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>
            新增发货单
          </el-button>
        </div>
      </div>
    </template>

    <!-- 发货单数据表格 -->
    <el-table border :data="deliveryOrderList" :show-overflow-tooltip="true" v-loading="loading" class="order-table"
      @selection-change="handleSelectionChange">
      <!-- 选择列 -->
      <el-table-column type="selection" width="55" />
      <!-- 发货单编号列 -->
      <el-table-column prop="delivery_number" label="发货单编号" width="150" />
      <!-- 发货日期列 -->
      <el-table-column prop="delivery_date" label="发货日期" width="110">
        <template #default="{ row }">
          {{ formatDate(row.delivery_date) }}
        </template>
      </el-table-column>
      <!-- 快递公司列 -->
      <el-table-column label="快递公司" min-width="150">
        <template #default="{ row }">
          {{ row.courier_name || (row.courier && row.courier.courier_name) || '-' }}
        </template>
      </el-table-column>
      <!-- 快递单号列 -->
      <el-table-column prop="tracking_number" label="快递单号" width="150" />
      <!-- 发货人列 -->
      <el-table-column prop="delivered_by" label="发货人" width="100" />
      <!-- 订单数量列 -->
      <el-table-column label="订单数量" width="100">
        <template #default="{ row }">
          {{ row.sales_orders ? row.sales_orders.length : 0 }}
        </template>
      </el-table-column>
      <!-- 发货单状态列 -->
      <el-table-column prop="status" label="发货单状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getDeliveryStatusTagType(row.status)">
            {{ getDeliveryStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- 操作列 -->
      <el-table-column label="操作" width="220" fixed="right">
        <template #default="{ row }">
          <!-- 查看详情按钮 -->
          <el-button type="info" size="small" @click="handleView(row)">
            查看详情
          </el-button>
          <!-- 编辑按钮 -->
          <el-button type="primary" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <!-- 删除按钮 -->
          <el-button type="danger" size="small" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination background layout="total, sizes, prev, pager, next, jumper" :total="total"
        :current-page="currentPage" :page-size="pageSize" :page-sizes="[10, 20, 30, 40, 100]"
        @current-change="handlePageChange" @size-change="handleSizeChange" />
    </div>
  </el-card>

  <!-- 发货单详情对话框 -->
  <el-dialog v-model="detailDialogVisible" title="发货单详情" width="800px" :close-on-click-modal="false">
    <div v-loading="detailLoading" class="detail-container">
      <!-- 发货单基本信息 -->
      <el-descriptions :column="2" border>
        <el-descriptions-item label="发货单编号">
          {{ deliveryOrderDetail.delivery_number || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="发货日期">
          {{ formatDate(deliveryOrderDetail.delivery_date) || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="快递公司">
          {{ deliveryOrderDetail.courier_name || (deliveryOrderDetail.courier && deliveryOrderDetail.courier.courier_name) || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="快递单号">
          {{ deliveryOrderDetail.tracking_number || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="发货人">
          {{ deliveryOrderDetail.delivered_by || '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="发货单状态">
          <el-tag :type="getDeliveryStatusTagType(deliveryOrderDetail.status)">
            {{ getDeliveryStatusText(deliveryOrderDetail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="订单数量">
          {{ deliveryOrderDetail.sales_orders ? deliveryOrderDetail.sales_orders.length : 0 }}
        </el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">
          {{ deliveryOrderDetail.notes || '-' }}
        </el-descriptions-item>
      </el-descriptions>

      <!-- 关联订单列表 -->
      <div class="related-orders-section">
        <h3>关联订单列表</h3>
        <el-table :data="deliveryOrderDetail.sales_orders" border max-height="300">
          <el-table-column prop="order_number" label="订单编号" width="150" />
          <el-table-column label="客户名称" min-width="150">
            <template #default="{ row }">
              {{ row.customer && row.customer.customer_name || '-' }}
            </template>
          </el-table-column>
          <el-table-column label="产品名称" min-width="150">
            <template #default="{ row }">
              {{ row.product && row.product.product_name || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="80" />
          <el-table-column prop="total_amount" label="订单金额" width="100">
            <template #default="{ row }">
              ¥{{ row.total_amount }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="订单状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getOrderStatusTagType(row.status)">
                {{ getOrderStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 新增/编辑发货单对话框 -->
  <DeliveryOrderEditDialog
    v-model:visible="editDialogVisible"
    v-model:deliveryOrder="editingDeliveryOrder"
    :courier-options="courierOptions"
    :loading="editLoading"
    :save-loading="saveLoading"
    @save="handleSave"
    @close="handleEditClose"
    @show-order-selection="showOrderSelectionDialog"
    @remove-order="removeOrder"
    @courier-change="onCourierChange"
  />

  <!-- 选择订单对话框 -->
  <OrderSelectionDialog
    v-model:visible="orderSelectionDialogVisible"
    :order-list="orderList"
    :loading="orderLoading"
    :total="orderTotal"
    :current-page="orderCurrentPage"
    :page-size="orderPageSize"
    :selected-rows="selectedOrderRows"
    v-model:search-form="orderSearchForm"
    :get-order-status-text="getOrderStatusText"
    :get-order-status-tag-type="getOrderStatusTagType"
    @search="handleOrderSearch"
    @reset="handleOrderReset"
    @page-change="handleOrderPageChange"
    @size-change="handleOrderSizeChange"
    @selection-change="handleOrderSelectionChange"
    @confirm="confirmOrderSelection"
  />
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus } from '@element-plus/icons-vue'

// 导入API
import {
  getDeliveryOrderList,
  getDeliveryOrderById,
  createDeliveryOrder,
  updateDeliveryOrder,
  deleteDeliveryOrder
} from '@/api/DeliveryOrders'

import { getOrderList } from '@/api/SalesOrders'
import { getCourierCompanyList } from '@/api/CourierCompanies'

// 导入配置
import orderStatusConfig from '@/utils/orderStatusConfig'

// 导入组件
import DeliveryOrderEditDialog from '@/components/DeliveryOrderEditDialog.vue'
import OrderSelectionDialog from '@/components/OrderSelectionDialog.vue'

// 发货单状态配置
const deliveryStatusOptions = [
  { value: 1, label: '待发货' },
  { value: 2, label: '已发货' },
  { value: 3, label: '已签收' }
]

// 获取发货单状态文本
const getDeliveryStatusText = (status) => {
  const statusOption = deliveryStatusOptions.find(option => option.value === status)
  return statusOption ? statusOption.label : '-'
}

// 获取发货单状态标签类型
const getDeliveryStatusTagType = (status) => {
  switch (status) {
    case 1: return 'info'   // 待发货
    case 2: return 'warning' // 已发货
    case 3: return 'success' // 已签收
    default: return 'info'
  }
}

// 获取订单状态文本
const getOrderStatusText = (status) => {
  return orderStatusConfig.getStatusLabel(status)
}

// 获取订单状态标签类型
const getOrderStatusTagType = (status) => {
  return orderStatusConfig.getStatusTagType(status)
}

// 响应式数据定义
const deliveryOrderList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedRows = ref([])

// 搜索表单数据
const searchForm = reactive({
  deliveryNumber: '',
  courierName: '',
  status: ''
})

// 详情对话框相关状态
const detailDialogVisible = ref(false)
const detailLoading = ref(false)
const deliveryOrderDetail = ref({})

// 编辑对话框相关状态
const editDialogVisible = ref(false)
const editLoading = ref(false)
const saveLoading = ref(false)
const editingDeliveryOrder = ref({
  delivery_id: '',
  delivery_date: '',
  courier_id: '',
  courier_name: '',
  tracking_number: '',
  delivered_by: '',
  notes: '',
  order_ids: []
})

// 快递公司选项
const courierOptions = ref([])

// 选择订单对话框相关状态
const orderSelectionDialogVisible = ref(false)
const orderList = ref([])
const orderLoading = ref(false)
const orderTotal = ref(0)
const orderCurrentPage = ref(1)
const orderPageSize = ref(10)
const selectedOrderRows = ref([])

// 订单搜索表单
const orderSearchForm = reactive({
  orderNumber: '',
  customerName: ''
})



// 格式化日期显示
const formatDate = (date) => {
  if (!date) return '-'
  const d = new Date(date)
  return d.toLocaleDateString('zh-CN')
}

// 处理表格行选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 获取发货单列表数据
const getDeliveryOrderListData = async () => {
  try {
    loading.value = true

    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      deliveryNumber: searchForm.deliveryNumber,
      courierName: searchForm.courierName,
      status: searchForm.status
    }

    const res = await getDeliveryOrderList(params)

    if (res.data && Array.isArray(res.data.deliveryOrders)) {
      deliveryOrderList.value = res.data.deliveryOrders
      total.value = res.data.pagination.totalCount || 0
      currentPage.value = res.data.pagination.currentPage || 1
      pageSize.value = res.data.pagination.pageSize || 10
    } else {
      deliveryOrderList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取发货单列表失败:', error)
    ElMessage.error('获取发货单列表失败，请稍后重试！')
    deliveryOrderList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 获取快递公司选项数据
const getCourierOptionsData = async () => {
  try {
    const res = await getCourierCompanyList({ pageSize: 1000 })
    courierOptions.value = res.data || []
  } catch (error) {
    console.error('获取快递公司数据失败:', error)
    ElMessage.error('获取快递公司数据失败，请稍后重试！')
  }
}

// 页码改变事件处理函数
const handlePageChange = (page) => {
  currentPage.value = page
  getDeliveryOrderListData()
}

// 每页条数改变事件处理函数
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getDeliveryOrderListData()
}

// 搜索按钮点击事件处理函数
const handleSearch = () => {
  currentPage.value = 1
  getDeliveryOrderListData()
}

// 重置按钮点击事件处理函数
const handleReset = () => {
  Object.assign(searchForm, {
    deliveryNumber: '',
    courierName: '',
    status: ''
  })
  currentPage.value = 1
  getDeliveryOrderListData()
}

// 查看发货单详情
const handleView = async (row) => {
  try {
    detailDialogVisible.value = true
    detailLoading.value = true

    const response = await getDeliveryOrderById(row.delivery_id)

    if (response.data) {
      deliveryOrderDetail.value = response.data
    } else {
      deliveryOrderDetail.value = response
    }
  } catch (error) {
    console.error('获取发货单详情失败:', error)
    ElMessage.error('获取发货单详情失败，请稍后重试！')
    deliveryOrderDetail.value = row
  } finally {
    detailLoading.value = false
  }
}

// 新增发货单按钮点击事件处理函数
const handleAdd = () => {
  // 重置编辑表单
  editingDeliveryOrder.value = {
    delivery_id: '',
    delivery_date: '',
    courier_id: '',
    courier_name: '',
    tracking_number: '',
    delivered_by: '',
    notes: '',
    order_ids: []
  }
  editDialogVisible.value = true
}

// 编辑发货单
const handleEdit = (row) => {
  // 填充编辑表单数据
  editingDeliveryOrder.value = {
    delivery_id: row.delivery_id || '',
    delivery_date: row.delivery_date || '',
    courier_id: row.courier_id || '',
    courier_name: row.courier_name || (row.courier && row.courier.courier_name) || '',
    tracking_number: row.tracking_number || '',
    delivered_by: row.delivered_by || '',
    notes: row.notes || '',
    order_ids: row.sales_orders ? row.sales_orders.map(order => order.order_id) : []
  }

  editDialogVisible.value = true
}

// 编辑对话框关闭事件处理函数
const handleEditClose = () => {
  // 新组件会处理表单重置，这里不需要做任何事情
}

// 保存发货单信息（新增或编辑）
const handleSave = async (deliveryOrder) => {
  try {
    saveLoading.value = true

    // 准备提交数据
    const submitData = {
      delivery_date: deliveryOrder.delivery_date,
      courier_id: deliveryOrder.courier_id,
      courier_name: deliveryOrder.courier_name,
      tracking_number: deliveryOrder.tracking_number,
      delivered_by: deliveryOrder.delivered_by,
      notes: deliveryOrder.notes,
      order_ids: deliveryOrder.order_ids
    }

    // 根据是否有delivery_id判断是新增还是编辑
    if (deliveryOrder.delivery_id) {
      // 编辑发货单
      submitData.delivery_id = deliveryOrder.delivery_id
      await updateDeliveryOrder(submitData)
      ElMessage.success('更新发货单成功！')
    } else {
      // 新增发货单
      await createDeliveryOrder(submitData)
      ElMessage.success('新增发货单成功！')
    }

    editDialogVisible.value = false
    getDeliveryOrderListData()
  } catch (error) {
    console.error('保存发货单失败:', error)
    ElMessage.error(`保存发货单失败：${error.msg || error.message || '请稍后重试！'}`)
  } finally {
    saveLoading.value = false
  }
}

// 删除发货单
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除发货单 "${row.delivery_number}" 吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteDeliveryOrder(row.delivery_id)
    ElMessage.success('删除发货单成功！')

    // 如果当前页只有一条数据且不是第一页，则回退到上一页
    if (deliveryOrderList.value.length === 1 && currentPage.value > 1) {
      currentPage.value = currentPage.value - 1
    }
    getDeliveryOrderListData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除发货单失败:', error)
      ElMessage.error('删除发货单失败，请稍后重试！')
    }
  }
}

// 当快递公司选择变化时
const onCourierChange = (courierId) => {
  const selectedCourier = courierOptions.value.find(courier => courier.courier_id === courierId)
  if (selectedCourier) {
    editingDeliveryOrder.value.courier_name = selectedCourier.courier_name
  } else {
    editingDeliveryOrder.value.courier_name = ''
  }
  // 创建新的对象以触发响应式更新
  editingDeliveryOrder.value = { ...editingDeliveryOrder.value }
}

// 显示订单选择对话框
const showOrderSelectionDialog = async () => {
  orderSelectionDialogVisible.value = true
  // 重置订单搜索条件
  Object.assign(orderSearchForm, {
    orderNumber: '',
    customerName: ''
  })
  orderCurrentPage.value = 1
  await getOrderListData()
}

// 获取订单列表数据
const getOrderListData = async () => {
  try {
    orderLoading.value = true

    const params = {
      page: orderCurrentPage.value,
      pageSize: orderPageSize.value,
      orderNumber: orderSearchForm.orderNumber,
      customerName: orderSearchForm.customerName,
      // 只显示未关联发货单的订单
      deliveryId: 'null',
      // 只显示已入库的订单（状态值为3）
      status: 3
    }

    const res = await getOrderList(params)

    if (res.data && Array.isArray(res.data.orders)) {
      orderList.value = res.data.orders
      orderTotal.value = res.data.pagination.totalCount || 0
      orderCurrentPage.value = res.data.pagination.currentPage || 1
      orderPageSize.value = res.data.pagination.pageSize || 10

      // 设置已选择的订单为选中状态
      // 新组件会处理选中状态，这里不需要做任何事情
    } else {
      orderList.value = []
      orderTotal.value = 0
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败，请稍后重试！')
    orderList.value = []
    orderTotal.value = 0
  } finally {
    orderLoading.value = false
  }
}

// 处理订单表格行选择变化
const handleOrderSelectionChange = (selection) => {
  selectedOrderRows.value = selection
}

// 订单页码改变事件处理函数
const handleOrderPageChange = (page) => {
  orderCurrentPage.value = page
  getOrderListData()
}

// 订单每页条数改变事件处理函数
const handleOrderSizeChange = (size) => {
  orderPageSize.value = size
  orderCurrentPage.value = 1
  getOrderListData()
}

// 订单搜索按钮点击事件处理函数
const handleOrderSearch = () => {
  orderCurrentPage.value = 1
  getOrderListData()
}

// 订单重置按钮点击事件处理函数
const handleOrderReset = () => {
  Object.assign(orderSearchForm, {
    orderNumber: '',
    customerName: ''
  })
  orderCurrentPage.value = 1
  getOrderListData()
}

// 确认订单选择
const confirmOrderSelection = () => {
  // 更新编辑表单中的订单ID列表
  editingDeliveryOrder.value.order_ids = selectedOrderRows.value.map(order => order.order_id)
  orderSelectionDialogVisible.value = false
}

// 移除订单
const removeOrder = (order) => {
  const index = editingDeliveryOrder.value.order_ids.indexOf(order.order_id)
  if (index > -1) {
    const newOrderIds = [...editingDeliveryOrder.value.order_ids]
    newOrderIds.splice(index, 1)
    editingDeliveryOrder.value.order_ids = newOrderIds
  }
}

// 组件挂载时获取数据
onMounted(() => {
  getDeliveryOrderListData()
  getCourierOptionsData()
})
</script>

<style scoped>
.search-container {
  margin-bottom: 20px;
}

.search-card {
  border: 1px solid #e4e7ed;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 0;
}

.search-form .el-form-item {
  margin-bottom: 0;
  flex: 0 0 auto;
}

.search-input {
  width: 150px;
}

.search-select {
  width: 150px;
}

.button-group {
  display: flex;
  gap: 10px;
  margin-left: auto !important;
}

.search-button,
.reset-button {
  white-space: nowrap;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.table-header span {
  font-size: 16px;
  font-weight: bold;
}

.table-header>div {
  display: flex;
  gap: 10px;
}

.order-table {
  width: 100%;
}

.pagination-container {
  text-align: right;
  margin-top: 20px;
}

.detail-container {
  min-height: 200px;
}

.dialog-footer {
  text-align: right;
}

.related-orders-section {
  margin-top: 20px;
}

.related-orders-section h3 {
  margin-bottom: 10px;
}

.selected-orders {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.no-orders {
  margin-top: 10px;
  color: #909399;
}

.order-selection-container {
  min-height: 400px;
}

@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
  }

  .search-form .el-form-item {
    width: 100%;
  }

  .search-input,
  .search-select {
    width: 100%;
  }

  .button-group {
    margin-left: 0 !important;
    width: 100%;
    justify-content: center;
  }

  .table-header {
    flex-direction: column;
    align-items: stretch;
  }

  .table-header>div {
    justify-content: center;
  }
}
</style>
